/*
 * Copyright 2011 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma.internal.reflection;

import java.security.SecureRandom;

import org.shalma.model.Id;

public class IdGenerator {

	public static final int ID_BYTES_SIZE = 16;

	private static SecureRandom numberGenerator;

	// TODO inline
	public static byte[] getId(Class<?> type) {

		Id annotation = type.getAnnotation(Id.class);
		if (annotation == null)
			throw new IllegalStateException("Null id for: " + type);

		return Base64.decode(annotation.value(), Base64.URL_SAFE
				| Base64.NO_PADDING);
	}

	public static byte[] make(int size) {

		SecureRandom ng = numberGenerator;
		if (ng == null)
			numberGenerator = ng = new SecureRandom();

		byte[] bytes = new byte[size];
		ng.nextBytes(bytes);

		return bytes;
	}

	static String createId() {
		return encodeURL(IdGenerator.make(ID_BYTES_SIZE));
	}

	public static String encodeURL(byte[] id) {
		return Base64.encodeToString(id, Base64.URL_SAFE | Base64.NO_PADDING);
	}

	public static byte[] decodeURL(String id) {
		return Base64.decode(id, Base64.URL_SAFE);
	}

	public static void main(String[] args) {

		for (int i = 0; i < 10; i++) {
			System.out.println(createId());
		}
	}

}
